<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        center
        :closable="false">
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps 
        :space="200"  
        :active="activeIndex - 0" 
        finish-status="success" 
        align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页区域 -->
      <el-form 
        :model="addForm" 
        :rules="addRules" 
        ref="addForm" 
        label-width="100px"
        label-position="top">
        <el-tabs 
          v-model="activeIndex" 
          :tab-position="tabPosition" 
          :before-leave="beforeTabsLeave"
          @tab-click="tabClick">

          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item type="number" label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item type="number" label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProp"
                @change="cateId">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品参数" name="1">
            <el-form-item 
              v-for="item in manyParams" 
              :key="item.attr_id" 
              :label="item.attr_name">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox 
                  v-for="(value,v) in item.attr_vals" 
                  :key="v" 
                  :label="value"
                  border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品属性" name="2">
            <el-form-item 
              v-for="item in onlyData" 
              :key="item.attr_id"
              :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品图片" name="3">
            <!-- action图片要上传到的后台api地址 -->
            <!-- 上传图片不能触发axios的token，需要使用upload的属性headers请求头获取token -->
            <!-- on-success图片上传成功后的一个钩子 -->
            <el-upload        
              action="https://lianghj.top:8888/api/private/v1/upload"
              :on-preview="showPreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>            
          </el-tab-pane>
          
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addBtn">添加商品</el-button>
          </el-tab-pane>

          <!-- 预览图片的对话框 -->
          <el-dialog
            title="预览图片"
            :visible.sync="previewDialogVisible"
            width="50%"
            @close="previewClose">
            <img :src="previewPath" alt="" width="100%" height="100%">
          </el-dialog>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name:'Add',
  data() {
    return {
      // 步骤条默认选中项的索引号
      activeIndex: '0',
      // tabs标签页的位置
      tabPosition: 'left',
      // 添加商品的表单数据
      addForm:{
        goods_name:'',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 选中的商品分类的id数组
        goods_cat:[],
        // 图片的数组
        pics:[],
        // 商品的内容
        goods_introduce:'',
        // 动态参数和静态属性的数组
        attrs:[]
      },
      addRules:{
        goods_name:[
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ],
        goods_price:[
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight:[
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number:[
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_cat:[
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ]
      },
      // 商品分类的数据
      cateList:[],
      cateProp:{
        value:'cat_id',
        label:'cat_name',
        children:'children',
        expandTrigger:'hover'
      },
      // 商品参数的数据
      manyParams:[],
      // 商品属性的数据
      onlyData:[],
      // 图片上传组件的headers请求头
      headerObj:{
        Authorization:sessionStorage.getItem('token')
      },
      // 预览图片的地址
      previewPath:'',
      // 控制图片对话框的展示与隐藏
      previewDialogVisible: false
    }
  },
  created(){
    this.getCateList()
  },
  methods: {
    // 获取商品分类
    async getCateList(){
      const {data:res} = await this.$http.get('categories')
      if(res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.cateList = res.data
    },
    // 级联选择器选中项发生变化时触发此函数
    cateId(){
      if(this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }     
    },
    // 切换tab标签之前触发此函数
    beforeTabsLeave(activeName, oldActiveName){
      if(oldActiveName === '0' && this.addForm.goods_cat.length !== 3){
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // tabs标签页切换时触发此函数
    async tabClick(){
      // '1' 表示tabs切换到商品参数
      if(this.activeIndex === '1'){
        const {data:res} = await this.$http.get('categories/' + this.addForm.goods_cat[2] + '/attributes',
        {params:{sel:'many'}}) 
        console.log(res);
        if(res.meta.status !== 200) return this.$message.error('获取商品动态参数失败')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyParams = res.data
      }
      // '2' 切换到商品属性
      if(this.activeIndex === '2'){
        const {data:res} = await this.$http.get('categories/' + this.addForm.goods_cat[2] + '/attributes',
        {params:{sel:'only'}}) 
        if(res.meta.status !== 200) return this.$message.error('获取商品静态属性失败')
        console.log(res)
        this.onlyData = res.data
      }
    },
    // 图片上传成功触发的事件
    handleSuccess(response){
      // 将后台返回的图片地址保存到表单中
      const picInfo = {pic: response.data.tmp_path} 
      this.addForm.pics.push(picInfo)
      console.log(this.addForm)
    },
    // 点击预览图片
    showPreview(file){
      //console.log(file)
      this.previewPath = file.response.data.url
      this.previewDialogVisible = true
    },
    // 移除图片的事件
    handleRemove(file){
      //console.log(file)
      // 1.找到要删除的图片的路径
      const filePath = file.response.data.tmp_path
      // 2.根据图片路径找到在数组中索引号
      const picIndex = this.addForm.pics.findIndex(x => x.pic === filePath)
      // 3.根据索引号删除指定图片
      this.addForm.pics.splice(picIndex,1)
      console.log(this.addForm)
    },
    // 预览图片对话框的关闭事件
    previewClose(){
      this.previewDialogVisible = false
    },
    // 添加商品
    addBtn(){
      this.$refs.addForm.validate(async value => {
        if(!value) return this.$message.error('请填写必要的表单项')
        // 添加商品请求中goods_cat是字符串形式，原来的数组需要转换，利用深拷贝
        const form = JSON.parse(JSON.stringify(this.addForm))
        form.goods_cat = form.goods_cat.join(',')       
        // 处理动态参数和静态属性
        this.manyParams.forEach(item => {
          const newMany = {attr_id: item.attr_id, attr_value: item.attr_vals.join(' ')}
          this.addForm.attrs.push(newMany)
        })
        this.onlyData.forEach(item => {
          const newMany = {attr_id: item.attr_id, attr_value: item.attr_vals}
          this.addForm.attrs.push(newMany)
        })
        form.attrs = this.addForm.attrs
        //console.log(form)
        const {data:res} = await this.$http.post('goods',form)
        console.log(res)
        if(res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    },
  },
}
</script>

<style lang="less" scoped>
div /deep/ .el-card{
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  margin-top: 15px;

  .el-steps{
    margin: 15px 0;
  }
  .el-step__title{
    font-size: 12px;
  } 

  .el-checkbox{
    margin: 0;
  }

  .quill-editor{
    margin: 0 0 15px 0;

    .ql-editor{
    min-height: 300px;
    }
  }
}
</style>